package com.uchedao.seller.ui.car.publish.baseinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.http.entity.DictEntity;
import com.uchedao.seller.http.response.ConfigDictResponse;
import com.uchedao.seller.inf.ICheckEntityListener;
import com.uchedao.seller.inf.ICheckValueListener;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.manager.DictionaryManager;
import com.uchedao.seller.module.AttachInfo;
import com.uchedao.seller.module.BaseInfo;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.module.TradeInfo;
import com.uchedao.seller.module.UseInfo;
import com.uchedao.seller.ui.car.publish.VehicleSelectActivity;
import com.uchedao.seller.ui.carlist.province_city.ProvinceCityActivity;
import com.uchedao.seller.util.CheckTextDateBtnValue;
import com.uchedao.seller.util.CheckValueUtil;
import com.uchedao.seller.util.Util;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Description:基本信息——车辆信息
 * Date: 2015-09-18  14:14
 * User: wushan
 */
public class BaseInfoCarInfoView extends UCheDaoRelativeLayout implements IOnResultBack {

    private static final int FROM_CAMERA_UP_LOADCARPACTURE = 101;// 拍照获取
    private static final int FROM_PICTURE_UP_LOADCARPACTURE  = 102;// 从图库获取
    private static final int FROM_SELECT_VEHICLE = 201;

    private BaseInfo baseInfo;

    public static final int REQUEST_PROVINCE = 600;// 请求省份
    public static final int REQUEST_CITY = 601;// 市
    public static final int REQUEST_CAR_BRAND = 602;// 品牌
    public static final int REQUEST_CAR_SERIES = 603;// 系列
    public static final int REQUEST_CAR_MODEL = 604;// 车型
    public static final int REQUEST_SCAN = 605;// 扫描二维码ID

//    public static final int TYPE_PROVINCE = 605;// 省
//    public static final int TYPE_CITY = 606;// 市
//    public static final int TYPE_CAR_BRAND = 2;// 品牌
//    public static final int TYPE_CAR_SERIES = 3;// 系列
//    public static final int TYPE_CAR_MODEL = 4;// 车型

    public static final String KEY_TYPE = "carSelect";// 类型

    public static final String KEY_PROVINCE = "province";// 省份ID

    public static final String KEY_BRAND_ID = "brandId";// 品牌ID

    public static final String KEY_SERIES_ID = "seriesId";// 系列ID

    public static final String KEY_DATA = "data";// 返回的数据

    private String tmpPath;// 临时图片路径
    private AlertDialog pickerDialog;// 图片选取对话框

    public BaseInfoCarInfoView(Context context) {
        super(context);
    }

    public BaseInfoCarInfoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseInfoCarInfoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean save() {

//        if (!Util.isCarPlateValid(tempCarPLate)) {
//            ToastUtil.showToast("请输入有效车牌号", true);
//            return false;
//        } else {
//            GlobalInfo.draft.car_plate = baseInfo.use_info.car_plate;
//            GlobalInfo.dbHelper.updateDrafCarPlateByByInfoId(GlobalInfo.draft.info_number, tempCarPLate);
//        }

        ContentValues values = new ContentValues();
        // values.put(DbHelper.KEY_BASE_INFO, baseInfo.toString());
        values.put(DbHelper.KEY_DRAFT_BASE_INFO, toJson(baseInfo));
        int status = baseInfo.getStatus();
        values.put(DbHelper.KEY_DRAFT_BASE_INFO_STATUS, status);

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.base_info = baseInfo.clone();
            GlobalInfo.draft.status[Draft.TYPE_BASE_INFO] = status;

            // 必填项全部填写返回true
            if(baseInfo.use_info.getStatus()==2 && baseInfo.trade_info.getStatus()==2 && baseInfo.attach_info.getStatus()==2)
                return true;
            else
                return false;
        }
        return false;
    }

    @Override
    public boolean dataChanged() {
        return !baseInfo.equals(GlobalInfo.draft.base_info);
//        return false;
    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        baseInfo = GlobalInfo.draft.base_info.clone();
    }

    private ImageView ivConfigForm;

    @Override
    public void initView() {
        final UseInfo useInfo = baseInfo.use_info;
        final TradeInfo tradeInfo = baseInfo.trade_info;
        final AttachInfo attchInfo = baseInfo.attach_info;

        LayoutInflater.from(mContext).inflate(R.layout.view_base_car_info, this);
        TextView subjectTv = (TextView) findViewById(
                R.id.base_car_info_title).findViewById(R.id.subject_tv);
        // 使用信息
        subjectTv.setText(R.string.base_use_info_subtitle);

        // 所在地
        CheckValueUtil.textBtnListener(this, R.id.base_reg_address_tv,
                R.id.base_reg_addr_province_bt, useInfo.province + " " + useInfo.city);
        Button base_reg_addr_province_bt = (Button) findViewById(R.id.base_reg_addr_province_bt);
        base_reg_addr_province_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity) mContext).startActivityForResult(new Intent(mContext, ProvinceCityActivity.class), REQUEST_PROVINCE);
            }
        });

        // 首次上牌时间
        Button base_first_card_time_bt = (Button) this
                .findViewById(R.id.base_first_card_time_bt);
        CheckValueUtil.textDateBtnListener(
                CheckTextDateBtnValue.TYPE_YEAR_MONTH,
                CheckTextDateBtnValue.DATE_PAST, this,
                R.id.base_first_card_time_tv, R.id.base_first_card_time_bt,
                useInfo.card_time, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.use_info.card_time = str;

                        // 车龄
                        Button base_car_age_bt = (Button) findViewById(R.id.base_car_age_bt);
                        if (TextUtils.isEmpty(baseInfo.use_info.card_time))
                            base_car_age_bt.setVisibility(View.INVISIBLE);
                        else {
                            base_car_age_bt.setVisibility(View.VISIBLE);

                            try {// 计算车龄
                                base_car_age_bt.setText(getCoty(str));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }

                    }

                    private String getCoty(String str) throws ParseException {
                        Calendar nowCalendar = Calendar.getInstance();
                        int nowYear = nowCalendar.get(Calendar.YEAR);
                        int nowMonth = nowCalendar.get(Calendar.MONTH);

                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
                        Date date = formatter.parse(str);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH);

                        int monthCount = (nowYear - year) * 12 + nowMonth - month;

                        if (monthCount == 0)
                            return "小于一个月";
                        int y = monthCount / 12;
                        int m = monthCount % 12;

                        return (y > 0 ? y + "年" : "") + (m > 0 ? m + "月" : "");
                    }
                });

        // 行驶里程
        CheckValueUtil.textEditListener(this, R.id.base_kilometer_tv,
                R.id.base_kilometer_et, useInfo == null ? ""
                        : useInfo.kilometer, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.use_info.kilometer = str;
                    }
                });

        // 车身颜色
        DictionaryManager.SyncDictCallback callback = new DictionaryManager.SyncDictCallback() {
            @Override
            public void syncCompleted(ConfigDictResponse.CarDict dictEntity) {
                if(dictEntity == null)
                    return;
                CheckValueUtil.textBtnListener(BaseInfoCarInfoView.this, R.id.base_car_color_tv,
                        R.id.base_car_color_bt, dictEntity.color,
                        useInfo.color, new ICheckEntityListener() {
                            @Override
                            public void getValue(View v, DictEntity entity) {
                                baseInfo.use_info.color_key = entity.key;
                                baseInfo.use_info.color = entity.caption;
                            }
                        });
            }
        };
        DictionaryManager.getDictInfo(mContext, callback);

        // 排放标准
        DictionaryManager.SyncDictCallback callback3 = new DictionaryManager.SyncDictCallback() {
            @Override
            public void syncCompleted(ConfigDictResponse.CarDict dictEntity) {
                if(dictEntity == null)
                    return;
                CheckValueUtil.textBtnListener(BaseInfoCarInfoView.this, R.id.base_displace_standard_tv,
                        R.id.base_displace_standard_bt, dictEntity.emission_standards,
                        baseInfo.use_info.emission_standards, new ICheckEntityListener() {
                            @Override
                            public void getValue(View v, DictEntity entity) {
                                baseInfo.use_info.emission_standards_key = entity.key;
                                baseInfo.use_info.emission_standards = entity.caption;
                            }
                        });
            }
        };
        DictionaryManager.getDictInfo(mContext, callback3);

        // 交易信息
        TextView subTradeTitle = (TextView) findViewById(R.id.base_trade_info_title).findViewById(R.id.subject_tv);
        subTradeTitle.setText(R.string.base_trade_info_title);

        // 过户次数
        DictionaryManager.SyncDictCallback callback1 = new DictionaryManager.SyncDictCallback() {
            @Override
            public void syncCompleted(ConfigDictResponse.CarDict dictEntity) {
                if(dictEntity == null)
                    return;
                CheckValueUtil.textBtnListener(BaseInfoCarInfoView.this, R.id.base_transfer_num_tv,
                        R.id.base_transfer_num_bt, dictEntity.transfer_num,
                        baseInfo.trade_info.transfer_num, new ICheckEntityListener() {
                            @Override
                            public void getValue(View v, DictEntity entity) {
                                baseInfo.trade_info.transfer_num_key = entity.key;
                                baseInfo.trade_info.transfer_num = entity.caption;
                            }
                        });
            }
        };
        DictionaryManager.getDictInfo(mContext, callback1);

        // 保险到期时间
        CheckValueUtil.textDateBtnListener(
                CheckTextDateBtnValue.TYPE_YEAR_MONTH,
                CheckTextDateBtnValue.DATE_PAST, this,
                R.id.base_insurance_time_tv, R.id.base_insurance_time_bt,
                baseInfo.trade_info.insurance_time, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.trade_info.insurance_time = str;
                    }

                    private String getCoty(String str) throws ParseException {
                        return "";
                    }
                });

        // 年检有效期
        CheckValueUtil.textDateBtnListener(
                CheckTextDateBtnValue.TYPE_YEAR_MONTH,
                CheckTextDateBtnValue.DATE_PAST, this,
                R.id.base_annual_survey_tv, R.id.base_annual_survey_time_bt,
                baseInfo.trade_info.year_check_time, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.trade_info.year_check_time = str;
                    }

                    private String getCoty(String str) throws ParseException {
                        return "";
                    }
                });

        // 买方到场
        CheckValueUtil.textBtnListener(this,
                R.id.base_buyer_live_tv, R.id.base_buyer_live_bt,
                R.array.boolean_need, TextUtils
                        .isEmpty(tradeInfo.buyer_live) ? "不需要"
                        : tradeInfo.buyer_live,
                new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.trade_info.buyer_live_key = "需要".equals(str)? "1" : "2";
                        baseInfo.trade_info.buyer_live = str;
                    }
                });

        // 提档时长
        CheckValueUtil.textEditListener(this, R.id.base_mention_day_tv,
                R.id.base_mention_day_et, tradeInfo == null ? ""
                        : tradeInfo.mention_day, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.trade_info.mention_day = str;
                    }
                });

        // 附加信息
        TextView subAttachTitle = (TextView) findViewById(R.id.base_attach_info_title).findViewById(R.id.subject_tv);
        subAttachTitle.setText(R.string.base_attach_info_title);

        // 裸车价格
        CheckValueUtil.textEditListener(this, R.id.base_naked_price_tv,
                R.id.base_naked_price_et, attchInfo == null ? ""
                        : attchInfo.naked_car_price, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.attach_info.naked_car_price = str;
                    }
                });

        // 购车全款
        CheckValueUtil.textEditListener(this, R.id.base_full_price_tv,
                R.id.base_full_price_et, attchInfo == null ? ""
                        : attchInfo.full_car_price, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.attach_info.full_car_price = str;
                    }
                });

        // 发票
        CheckValueUtil.textBtnListener(this,
                R.id.base_invoice_tv, R.id.base_invoice_bt,
                R.array.have_entries, TextUtils
                        .isEmpty(attchInfo.invoice) ? "无"
                        : attchInfo.invoice,
                new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.attach_info.invoice_key = "有".equals(str)? "1" : "0";
                        baseInfo.attach_info.invoice = str;
                    }
                });

        // 配置单图片
        ivConfigForm = (ImageView) findViewById(R.id.base_config_form_pic);
        setBitmap(attchInfo.config_form_path);
        ivConfigForm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerDialog();
            }
        });

        // 配置单
        CheckValueUtil.textBtnListener(this,
                R.id.base_config_form_tv, R.id.base_config_form_bt,
                R.array.have_entries, TextUtils
                        .isEmpty(attchInfo.config_form) ? "无"
                        : attchInfo.config_form,
                new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        baseInfo.attach_info.config_form = str;
                        if("有".equals(str)) {
                            baseInfo.attach_info.config_form_key = "1";
                            ivConfigForm.setVisibility(View.VISIBLE);
                        } else {
                            baseInfo.attach_info.config_form_key = "0";
                            ivConfigForm.setVisibility(View.GONE);
                        }
                    }
                });

        // 车况描述
        // 附加信息
        TextView subDescTitle = (TextView) findViewById(R.id.base_desc_info_title).findViewById(R.id.subject_tv);
        subDescTitle.setText(R.string.base_vehicle_desc);

        CheckValueUtil.textBtnListener(this, R.id.base_desc_tv,
                R.id.base_desc_bt, baseInfo.desc_info);
        Button base_desc_bt = (Button) findViewById(R.id.base_desc_bt);
        base_desc_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)mContext).startActivityForResult(new Intent(mContext, VehicleSelectActivity.class), FROM_SELECT_VEHICLE);
            }
        });
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initListener() {

    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog() {
        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(mContext).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                takePhoto();
                            } else {
                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
                                ((Activity)mContext).startActivityForResult(intent, FROM_PICTURE_UP_LOADCARPACTURE);
                            }
                        }
                    }).create();
        }
        pickerDialog.show();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        tmpPath = file.getAbsolutePath();
        Uri uri = Uri.fromFile(file);
        i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        ((Activity)mContext).startActivityForResult(i, FROM_CAMERA_UP_LOADCARPACTURE);
    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        System.out.println("ws----view中" + "requestCode = " + requestCode + " resultCode = " + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PROVINCE:
                    Bundle b = data.getExtras();
                    // 保存省份ID
                    baseInfo.use_info.province_id = b.getInt("provinceId");
                    baseInfo.use_info.province = b.getString("provinceName");

                    baseInfo.use_info.city_id = b.getInt("cityId");
                    baseInfo.use_info.city = b.getString("cityName");

                    Button base_reg_addr_province_bt = (Button) findViewById(R.id.base_reg_addr_province_bt);
                    base_reg_addr_province_bt.setText(b.getString("provinceName") + " " + b.getString("cityName"));

//                    ((Button) findViewById(R.id.base_reg_addr_city_bt)).setText("");// 重新设置省份后，城市为空
                    break;

                case FROM_CAMERA_UP_LOADCARPACTURE:
                    setBitmap(tmpPath);
                    break;

                case FROM_PICTURE_UP_LOADCARPACTURE:
                    // dat=content://com.android.providers.media.documents/document/image:944
                    Uri uri = data.getData();
                    tmpPath = Util.getPath(mContext, uri);
                    L.i("uri = " + uri.toString() + " path=" + tmpPath);
                    setBitmap(tmpPath);
                    break;

                case FROM_SELECT_VEHICLE:
                    baseInfo.desc_info = data.getStringExtra("data");
                    ((TextView) findViewById(R.id.base_desc_bt)).setText(baseInfo.desc_info);
                    break;
            }
        }
    }

    public void setBitmap(String path) {
        if(TextUtils.isEmpty(path))
            return;
        Bitmap bmp = Util.getimage(path, 329, 249);
        if(bmp != null) {
            ivConfigForm.setImageBitmap(bmp);
            baseInfo.attach_info.config_form_path = path;
        }
    }
}
